#!/usr/bin/env bash

SERVER_NAME=kafka
IMAGE_NAME=bitnami/kafka
VERSION=3.7.0
PORT=9092
PASSWORD=kafka2024
DIR=/home/app/$SERVER_NAME

if [ -d "./Dockerfile" ]; then
  echo "Find Dockerfile.Will build docker images."
  docker build -t $IMAGE_NAME:$VERSION ./
fi

if [ ! -d "$DIR" ]; then
  mkdir -p $DIR;
  echo "dir $DIR create successful."
else
  echo "dir $DIR already exist.Will use it."
fi

echo "remove old container"

EM_RUN=$(docker ps| grep $SERVER_NAME|awk 'NR==1'|awk '{print $1}')
EM=$(docker ps -a | grep $SERVER_NAME|awk 'NR==1'|awk '{print $1}')

if [ -n "$EM_RUN" ]; then
  echo "container $EM_RUN is running.will stop and delete it."
  docker stop "$EM_RUN"
  docker rm "$EM_RUN"
elif [ -n "$EM" ]; then
  echo "container $EM is stop,but container is exists,will only delete it."
  docker rm "$EM"
else
  echo "Not find container $SERVER_NAME"
fi

# KRAFT 模式不依赖kafka
docker run -d --name $SERVER_NAME \
-p $PORT:$PORT \
-e KAFKA_ENABLE_KRAFT=true \
-e KAFKA_CFG_NODE_ID=0 \
-e KAFKA_KRAFT_CLUSTER_ID=Uu3NlUZ5TBaUEL-Ld8hC1g \
-e KAFKA_CFG_PROCESS_ROLES=controller,broker \
-e KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=0@localhost:9093 \
-e KAFKA_CFG_LISTENERS=SASL_SSL://:9092,CONTROLLER://:9093 \
-e KAFKA_CFG_ADVERTISED_LISTENERS=SASL_SSL://localhost:9092 \
-e KAFKA_CLIENT_USERS=kafka \
-e KAFKA_CLIENT_PASSWORDS=$PASSWORD \
-e KAFKA_CLIENT_LISTENER_NAME=SASL_SSL \
-e KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:SASL_PLAINTEXT,SASL_SSL:SASL_SSL \
-e KAFKA_CFG_SASL_MECHANISM_CONTROLLER_PROTOCOL=PLAIN \
-e KAFKA_CONTROLLER_USER=kafka \
-e KAFKA_CONTROLLER_PASSWORD=$PASSWORD \
-e KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER \
-e KAFKA_TLS_TYPE=JKS \
-e KAFKA_CERTIFICATE_PASSWORD=$PASSWORD \
-e KAFKA_INTER_BROKER_USER=kafka \
-e KAFKA_INTER_BROKER_PASSWORD=$PASSWORD \
-e KAFKA_CFG_INTER_BROKER_LISTENER_NAME=SASL_SSL \
-e KAFKA_CFG_SASL_MECHANISM_INTER_BROKER_PROTOCOL=PLAIN \
-v $DIR/truststore/server.keystore.jks:/opt/bitnami/kafka/config/certs/kafka.keystore.jks:ro \
-v $DIR/truststore/server.truststore.jks:/opt/bitnami/kafka/config/certs/kafka.truststore.jks:ro \
--restart=always $IMAGE_NAME:$VERSION
